package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pojo.Category;
import com.service.CategoryService;
import com.util.Page;

@Controller
@RequestMapping("")
public class CategoryController {

	
	@Autowired
	CategoryService categoryService;
	
	@RequestMapping("/listCategory")
	public ModelAndView listCategory(Page page) {
		
		ModelAndView modelAndView = new ModelAndView();
		PageHelper.offsetPage(page.getStart(), 5);
		List<Category> categories = categoryService.list();
		int total = (int) new PageInfo<Category>(categories).getTotal();
		
		page.caculateLast(total);
		
		// 传入转发的参数
		modelAndView.addObject("cs", categories);
		// 放如jsp路径
		modelAndView.setViewName("listCategory");
		
		return modelAndView;
	}
	
	
	
	@ResponseBody
	@RequestMapping("/submitCategory")
	public String submitCategory(@RequestBody Category category) {
		
		System.out.println("ssm接受浏览器提交json，并且转换为Category对象：" + category);
		return "ok";
	}
	
	
	@ResponseBody
	@RequestMapping("/getOneCategory")
	public String getOneCategory() {
		Category c = new Category();
		c.setId(100);
		c.setName("jsonCategory");
		
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("category", JSONObject.toJSON(c));
		
		return jsonObject.toJSONString();
	}
	
	
	@ResponseBody
	@RequestMapping("/getManyCategory")
	public String getManyCategory() {
		List<Category> cs = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Category c = new Category();
            c.setId(i);
            c.setName("分类名称:"+i);
            cs.add(c);
        }
        
        return JSONObject.toJSON(cs).toString();
	}
}
